package org.yuanqiframework.yuanqi.core.utils.xml;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * @Author 曹波涛
 * @Date 2022/10/11 10:01
 * @Version 1.0
 */
public class XmlUtils {
    private static final String PREFIX_XML = "<xml>";
    private static final String SUFFIX_XML = "</xml>";
    private static final String PREFIX_CDATA = "<![CDATA[";
    private static final String SUFFIX_CDATA = "]]>";

    /**
     * 转化成xml, 单层无嵌套
     *
     * @param param
     * @param isAddCdata
     * @return
     */
    public static String map2Xml(Map<String, String> param, boolean isAddCdata) {
        StringBuilder sb = new StringBuilder(PREFIX_XML);
        if (null != param) {
            for (Entry<String, String> entry : param.entrySet()) {
                sb.append("<").append(entry.getKey()).append(">");
                if (isAddCdata) {
                    sb.append(PREFIX_CDATA);
                    if (null != entry.getValue()) {
                        sb.append(entry.getValue());
                    }
                    sb.append(SUFFIX_CDATA);
                } else {
                    if (null != entry.getValue()) {
                        sb.append(entry.getValue());
                    }
                }
                sb.append("</").append(entry.getKey()).append(">");
            }
        }
        return sb.append(SUFFIX_XML).toString();
    }

    public static String map2Xml(Map<String, String> param) {
        return map2Xml(param, false);
    }

    /**
     * @param xml
     * @return Map
     * @description 将xml字符串转换成map
     */
    public static Map<String, Object> xml2Map(String xml) throws DocumentException {
        if (xml == null || "".equals(xml)) {
            return null;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        // 将xml格式的字符串转换成Document对象
        Document doc = DocumentHelper.parseText(xml);
        // 获取根节点
        Element root = doc.getRootElement();
        // 获取根节点下的所有元素
        List<?> children = root.elements();
        // 循环所有子元素
        if (children != null && children.size() > 0) {
            for (Object o : children) {
                Element child = (Element) o;
                map.put(child.getName(), child.getTextTrim());
            }
        }
        return map;
    }
}
